package gr.atc.epart;

import gr.atc.epart.actions.Action;
import gr.atc.epart.actions.Action.Type;
import gr.atc.epart.net.ActionsPage;
import gr.atc.epart.net.ActionsPage.SortBy;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ActionsAdapter extends ArrayAdapter<Action> {

	Handler uiHandler = new Handler();
	UIUpdateTask updateTask;

	private List<Action> _items;
	int page = 0;
	private Context context;
	ProgressDialog progressDialog;
	int totalPages;

	public ActionsAdapter(Context context, int textViewResourceId,
			ArrayList<Action> items) {
		super(context, textViewResourceId, items);

		this._items = items;
		this.context = context;
		updateTask = new UIUpdateTask();
		totalPages = 1;

	}

	public View getView(int position, View convertView, ViewGroup parent) {

		// View v = convertView;
		View v = null;

		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		int last = (getCount() - 1);

//		Log.v("adapter", "-----------------------------------");
//		Log.v("adapter", "getView: last = " + last);
//		Log.v("adapter", "getView: position = " + position);
//		Log.v("adapter", "-----------------------------------");
//
//		if (position == last) {
//
//
//			Log.v("adapter", "position == last");
//			v = new SimpleView(context);
//
//			page++;
//
//			// update(null, null, "all", null, null, "Popularity", "All",
//			// "Popular");
//
//			FetchThread fetchThread = new FetchThread();
//			fetchThread.start();
//
//			// uiHandler.post(updateTask);
//
//		} else {


			if (v == null) {

				v = inflater.inflate(R.layout.listviewrow, null);
			}

			Action action = _items.get(position);
			if (action != null) {
				TextView actionName = (TextView) v
						.findViewById(R.id.action_name);
				TextView actionCreationDate = (TextView) v
						.findViewById(R.id.action_creationdate);
				TextView actionCreator = (TextView) v
						.findViewById(R.id.action_creator);
				TextView actionDescription = (TextView) v
						.findViewById(R.id.action_description);
				Type type = action.getType();

				ImageView img = (ImageView) v.findViewById(R.id.action_image);
				if (type == Type.Deliberation) {
					img.setImageResource(R.drawable.ic_deliberations);
				} else if (type == Type.ePetition) {
					img.setImageResource(R.drawable.ic_petition);
				} else if (type == Type.Event) {
					img.setImageResource(R.drawable.ic_events);
				} else if (type == Type.Survey) {
					img.setImageResource(R.drawable.ic_survey);
				}

				if (actionName != null)
					actionName.setText(action.getName());

				if (actionCreator != null)
					actionCreator.setText(action.getCreator().getName());

				if (actionCreationDate != null) {
					SimpleDateFormat formatter = new SimpleDateFormat(
							"dd-MM-yyyy");
					actionCreationDate.setText(formatter.format(action
							.getDateCreated()));
				}

				if (actionDescription != null)
					actionDescription.setText(action.getDescription());

			}
//		}

		return v;
	}

	public int getTotalPages() {
		return totalPages;
	}

	public void setTotalPages(int totalPages) {
		this.totalPages = totalPages;
	}

	public Action getItem(int position) {
		return _items.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	private void update(String _nameString, String _tagsString,
			String _creatorString, String _fromString, String _toString,
			String _sortByString, String _typeString, String tabTag) {

		SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");

		Date _startDate = null;
		Date _endDate = null;

		try {
			if (_fromString != null && !_fromString.equals("")) {
				_startDate = formatter.parse(_fromString);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		try {
			if (_toString != null && !_toString.equals("")) {
				_endDate = formatter.parse(_toString);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Type type = Type.valueOf(_typeString);
		String[] _tags;
		if (_tagsString != null) {
			_tags = _tagsString.split(" ");
		} else {
			_tags = null;
		}

		EPartClient client = new EPartClient();
		ActionsPage actions = client.getActions(type, null,_creatorString,
				_startDate, _endDate, _tags, SortBy.Popularity, page, 10);

		if (actions != null) {
			_items.addAll(actions.getActions());
		}
		// this.notifyDataSetChanged();

	}

	@Override
	public int getCount() {
//		return _items.size() + 1;
		return _items.size();

	}

	public void showProgressDialog() {

		progressDialog = new ProgressDialog(context);
		progressDialog.setMessage("Please wait...");
		progressDialog.setIndeterminate(true);
		progressDialog.setCancelable(false);
		progressDialog.show();

	}

	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
		}
	};

	private class FetchThread extends Thread {

		public void run() {

			update(null, null, "all", null, null, "Popularity", "All",
					"Popular");

			uiHandler.post(updateTask);

		}
	}

	class UIUpdateTask implements Runnable {
		public void run() {
			Log.d("adapter", "UI update Task called...");
			notifyDataSetChanged();
		}
	}

	class SimpleView extends LinearLayout {

		public SimpleView(Context context) {

			super(context);

			this.setOrientation(HORIZONTAL);
			LinearLayout.LayoutParams cityParams = new LinearLayout.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
			cityParams.setMargins(1, 1, 1, 1);

			TextView cityControl = new TextView(context);
			cityControl.setText("Getting data...");
			cityControl.setTextSize(20f);
			addView(cityControl, cityParams);

		}
	}

}
